const API = require('../../utils/api.js'); // 引入封装好的 API 方法
Page({
  data: {
    messages: [], // 存储聊天记录
    inputValue: '', // 输入框的值
    scrollToView: '', // 用于滚动到最新的消息,
    userInfo:{},
    keyboardHeight:''
  },
  onInput(e) {
    this.setData({
      inputValue: e.detail.value
    });
  },
  sendMessage() {
    const { inputValue, messages } = this.data;
    if (inputValue.trim() === '') {
      return; // 如果输入为空，不发送
    }
    // 将用户的消息添加到聊天记录中
    const userMessage = { type: 'user', content: inputValue };
    this.setData({
      messages: [...messages, userMessage],
      inputValue: '', // 清空输入框
      scrollToView: 'message' + userMessage.id // 滚动到最新消息
    });
    // 模拟发送消息到后端并获取回复
    this.getBotResponse(inputValue);
  },

 async getBotResponse(userInput) {
    let resMsg= await API.chatAi({input:userInput},{timeout:30000});
    const { messages } = this.data;
    const botResponse = resMsg; 
    const botMessage = { type: 'bot', content: botResponse };
    this.setData({
      messages: [...messages, botMessage],
    });
    
  },
  onShow(){
    const { messages } = this.data;
    const botResponse = "欢迎进入客服界面..."; 
    const botMessage = { type: 'bot', content: botResponse };
    this.setData({
      messages: [...messages, botMessage],
    });
  },
  onLoad(){
    const app = getApp();
    this.setData({
      userInfo:app.globalData.userInfo
    })
  },
  //监听输入法高度
  // onKeyboardHeightChange(e) {
  //   const keyboardHeight = e.detail.height; // 输入法高度
  //   this.setData({
  //     keyboardHeight: keyboardHeight
  //   });
  // }
});